import request from '../../utils/request'

Page({
  data: {
    avatarUrl: '', // 头像URL
    nickname: '',  // 昵称
    cellphone: '',  // 手机号
    paths: [],
    showStatistics: false,
    showStyleConfig: false
  },
  onLoad() {
    const token = wx.getStorageSync('token');
    if (!token) {
      // 如果未登录，跳转到登录页
      wx.reLaunch({
        url: '/pages/login/login'  // 使用 reLaunch 清除页面栈，避免显示返回主页
      });
    }

    this.fetchUserInfo();
    this.loadCurrentPlan();

  },
  fetchUserInfo() {
    request({
      url: 'auth/info',
      method: 'GET'
    }).then(res => {
      console.log(res);
      const data = res.data;
      this.setData({
        avatarUrl: data.avatar?.url || '',
        nickname: data.nickname || '',
        cellphone: data.cellphone || '',
        paths: data.paths || [],
        showStatistics: this.hasPermission(data.paths || [], 'statistics'),
        showStyleConfig: this.hasPermission(data.paths || [], 'style_config'),
        showPremControl: this.hasPermission(data.paths || [], 'prem_control')
      });
    }).catch((err) => {
      console.error('请求 auth/info 接口失败:', err); // ✅ 打印异常详情
      wx.showToast({
        title: '请求失败，请检查网络',
        icon: 'none'
      });
    }).finally(() => {
      wx.hideLoading();
    });
  },
  // ✅ 权限判断工具函数
  hasPermission(paths, key) {
    return paths.includes(key);
  },
  loadCurrentPlan() {
    request({
      url: 'material/plan',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        const data = res.data || { tags: [], content: '' };
        this.setData({
          currentPlan: data
        });
      } else {
        wx.showToast({
          title: res.message || '获取素材计划失败',
          icon: 'none'
        });
      }
    }).catch(() => {
      wx.showToast({
        title: '获取素材计划失败',
        icon: 'none'
      });
    }).finally(() => {
      wx.hideLoading();
    });
  },
  handleCopyContent() {
    wx.setClipboardData({
      data: this.data.currentPlan.content,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        });
      }
    });
  },


  handleLogout() {
    wx.showLoading({
      title: '正在退出登录...',
      mask: true
    });
  
    request({
      url: 'auth/logout',
      method: 'DELETE'
    })

    // 延迟 1 秒后执行清除和跳转逻辑
    setTimeout(() => {
      // 清除本地缓存
      wx.removeStorageSync('token');
      wx.removeStorageSync('phone');
  
      // 清除全局变量
      const app = getApp();
      app.globalData.userInfo.token = '';
  
      // 跳转到登录页
      wx.redirectTo({
        url: '/pages/login/login',
        success() {
          wx.hideLoading(); // 页面跳转成功后关闭 loading
        },
        fail(err) {
          wx.hideLoading(); // 无论是否成功都要关闭 loading
          wx.showToast({ title: '跳转失败', icon: 'none' });
          console.error('跳转失败', err);
        }
      });
    }, 500); // 延迟 1000 毫秒（即 1 秒）
  },
  goToMaterialAdd() {
    wx.navigateTo({
      url: '/pages/materialAdd/materialAdd'
    });
  },
  goToMaterialAdd2() {
    wx.navigateTo({
      url: '/pages/add/add'
    });
  },
  goToCommodityMaterialAdd(){
    wx.navigateTo({
      url: '/pages/commodityAdd/commodityAdd'
    });
  },

  goToCommodityMaterialDetail(){
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail'
    });
  },

  goToSelectImage(){
    wx.navigateTo({
      url: '/pages/selectImage/selectImage'
    });
  },

  goToUpdPrompt(){
    wx.navigateTo({
      url: '/pages/updPrompt/upd'
    });
  },

  goToPremCtrl(){
    wx.navigateTo({
      url: '/pages/permCtrl/permCtrl'
    });
  },


  goToAnnotate() {
    wx.navigateTo({
      url: '/pages/annotate/annotate'
    });
  },
  goToAnnotate2() {
    wx.navigateTo({
      url: '/pages/annotation2/annotation2'
    });
  },

  goToRecord() {
    wx.navigateTo({
      url: '/pages/commodity_record/commodity_record'
    });
  }
})
